package com.example.nonggo.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.example.nonggo.Constants;
import com.example.nonggo.R;
import com.example.nonggo.base.BaseMvpFragment;
import com.example.nonggo.contract.HomeContract;
import com.example.nonggo.model.HomeModel;
import com.example.nonggo.presenter.HomePresenter;
import com.example.nonggo.utils.CustomToastUtils;
import com.example.nonggo.utils.NetworkUtils;
import com.example.nonggo.utils.PermissionUtils;
import com.example.nonggo.view.act.QuestionDetailActivity;
import com.example.nonggo.widget.WaveformView;

import java.io.File;

public class HomeFragment extends BaseMvpFragment<HomeContract, HomePresenter> implements HomeContract {
    private static final int REQUEST_RECORD_AUDIO_PERMISSION = 200;
    private volatile MediaRecorder mRecorder;
    private static final String TAG = HomeFragment.class.getName();
    private boolean isRecording = false;
    private View rootView;
    private File audioFile;

    private Handler handler;
    private Runnable updateWaveformRunnable;

    WaveformView waveformView;
    private TextView newQuestion;
    private TextView tvQuestion;
    long lastFinishTime = 0;
    long startRecordTime = 0;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        Log.d("HomeFragment", "onCreate");
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }


    @Override
    protected HomePresenter createPresenter() {
        return new HomePresenter(new HomeModel());
    }

    // 实现懒加载
    @Override
    protected void onLazyLoad(boolean isFirstLoad) {
        if (!NetworkUtils.isNetworkAvailable(rootView.getContext())) {
            CustomToastUtils.showCustomToast("网络不可用，请检查网络连接");
            return;
        }
        if (isFirstLoad) {//第一次显示才加载
            Log.e("HomeFragment", "onLazyLoad");
            presenter.getQuest();
        }
    }

    @Override
    public void showLoading() {
        rootView.findViewById(R.id.pb_loading).setVisibility(View.VISIBLE);
    }
    public void hideLoading() {
        rootView.findViewById(R.id.pb_loading).setVisibility(View.GONE);
    }

    @Override
    protected void initView(View rootView) {
        this.rootView = rootView;
        Log.e("HomeFragment", "initView");
        tvQuestion = rootView.findViewById(R.id.tv_question);
        newQuestion = rootView.findViewById(R.id.btn_new_question);
        FrameLayout micMaskLayout = rootView.findViewById(R.id.mic_mask_layout);
        micMaskLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                micMaskLayout.setVisibility(View.GONE);
                stopRecordingAndTranscribe();
            }
        });

        waveformView = rootView.findViewById(R.id.waveformView);
        // 初始化 Handler
        handler = new Handler();
        // 初始化 Runnable
        updateWaveformRunnable = new Runnable() {
            @Override
            public void run() {
                // 更新波形
                updateWaveform(rootView);
                handler.postDelayed(this, 250); // 每 250 毫秒更新一次
            }
        };

        newQuestion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startRecording(rootView);
            }
        });

        tvQuestion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), QuestionDetailActivity.class);
                intent.putExtra(Constants.QUESTION_TITLE, tvQuestion.getText());
                startActivity(intent);
            }
        });
    }

    private void updateWaveform(View rootView) {
        if (!isRecording) return;
        int maxAmplitude = mRecorder.getMaxAmplitude();
        int db = maxAmplitude / 35;
        Log.e(TAG, "分贝:" + db);
        db = Math.min(200, db);
        if (waveformView == null) {
            waveformView = rootView.findViewById(R.id.waveformView);
        }
        // 无声超过10分贝并且大于10秒则停止录音
        if (db < 10) {
            if (System.currentTimeMillis() - lastFinishTime > 10000) {
                stopRecordingAndTranscribe();
            }
        } else {
            lastFinishTime = System.currentTimeMillis();
        }

        // 更新波形视图
        waveformView.addVoiceSize(db);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_RECORD_AUDIO_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startRecording(rootView);
            } else {
                // 处理权限被拒绝的情况
                Log.e(TAG, "录音权限被拒绝");
            }
        }
    }

    private void startRecording(View rootView) {
        if (!NetworkUtils.isNetworkAvailable(rootView.getContext())) {
            CustomToastUtils.showCustomToast("网络不可用，请检查网络连接");
            return;
        }
        lastFinishTime = System.currentTimeMillis();
        startRecordTime = lastFinishTime;
        audioFile = new File(rootView.getContext().getFilesDir() + "/" + "voice_" + System.currentTimeMillis() + ".wav");
        try {
            if (ActivityCompat.checkSelfPermission(rootView.getContext(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                PermissionUtils.requestPermissions(this.getActivity(), PermissionUtils.getPermissions(), REQUEST_RECORD_AUDIO_PERMISSION);
                return;
            }
            if (mRecorder != null) {
                mRecorder.reset();
            } else {
                mRecorder = new MediaRecorder();
            }
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mRecorder.setAudioChannels(1);
            mRecorder.setAudioSamplingRate(16000);

            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    mRecorder.setOutputFile(audioFile);
                }
                mRecorder.prepare();
                mRecorder.start();
            } catch (Exception e) {
                mRecorder.release();
                mRecorder = null;
//                toast("录音失败");
                return;
            }
            isRecording = true;
            rootView.findViewById(R.id.mic_mask_layout).setVisibility(View.VISIBLE);
            handler.post(updateWaveformRunnable); // 启动 Runnable
        } catch (Exception e) {
            Log.d(TAG, "startRecording: ");
        }
    }

    private void stopRecordingAndTranscribe() {
        View micMaskLayout = this.rootView.findViewById(R.id.mic_mask_layout);
        if (micMaskLayout.getVisibility() != View.GONE) {
            micMaskLayout.setVisibility(View.GONE);
        }
        if (mRecorder != null) {
            isRecording = false;
            mRecorder.stop();//停止时没有prepare，就会报stop failed
            mRecorder.reset();
            mRecorder.release();
            mRecorder = null;
            handler.removeCallbacks(updateWaveformRunnable);
            // 录音小于2秒则不进行识别
            if (System.currentTimeMillis() - startRecordTime < 2000) {
                CustomToastUtils.showCustomToast("录音时间太短");
                return;
            }
            showLoading();
            // 这里可以调用语音转文字的API
            presenter.fileTranslateText(audioFile.getAbsolutePath());
        }
    }

    @Override
    public void jumpToContinueAsk(String data) {
        hideLoading();
        if (data == null || data.isEmpty()) {
            CustomToastUtils.showCustomToast("识别失败，请说慢一点");
            return;
        }
        tvQuestion.setText(data);
        Intent intent = new Intent(getActivity(), QuestionDetailActivity.class);
        intent.putExtra(Constants.QUESTION_TITLE, data);
        startActivity(intent);
    }

    @Override
    public void getQuestionSuccess(String question) {
        tvQuestion.setText(question);
    }
}
